#!/usr/bin/env python
#
'''
Routines and exception class to deal with non zero stus values
'''
import sys

import ctypes
import cfitsio

class FitsIOError(Exception):
    '''Exception class for non-zero status when calling CFITSIO functions.

    Maybe define an exception class for each status?
    
    Attributes:
    status: CFITSIO status value as python int (not c_int)
    errmsg: CFITSIO message string that goes with status
    filename: the name of the FITS file (if any) that gave the status
    stdmsg: custom message string for the exception class

    '''

    def __init__(self, status, errmsg):
        '''Initialize with status, error message and file name'''
        
        self.status = status
        self.errmsg = errmsg

        # Construct an error message string representative of this class
        self.stdmsg = 'Status=' + str(status) + ' ' + errmsg 

    def __str__(self):
        return self.stdmsg

    def __repr__(self):
        return self.stdmsg

# Exception factory
def handle_error(status):
    '''New function to raise FitsIOError given the FITSIO status
    @param ff: pointer to cfitsio.fitsfile()
    @param status: FITSIO status.
    '''

    # Standard CFITSIO error message text
    errtext = ctypes.create_string_buffer('\000' * cfitsio.FLEN_STATUS)
    cfitsio.ffgerr(status.value, errtext)

    # Create exception object.
    # Note that an exception will be thrown even for a zero status
    raise FitsIOError(status.value, errtext.value)

def check_error(status):
    if status.value != 0:
        handle_error(status)
